package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.entity.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器
 *      作用:
 *          用来判断是否为登录状态,如果为未登录状态,部分页面无法访问.
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    public void destroy() {
    }

    //专门用来匹配url地址的一个类,可以将*转义
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {


        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //设置放行的路径
        String[] urls = {"/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};

        //拿到当前请求的地址
        String requestURI = request.getRequestURI();


        //循环遍历放行的路径,判断当前请求地址是否在放行路径中
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)){
                //放行
                chain.doFilter(request,response);
                return;
            }
        }

        /*
        老方法,会造成IO流异常,
        for (String url : urls) {
            if (requestURI.contains(url)){
                chain.doFilter(req,resp);
                return;
            }
        }*/

        //拿到登录时保存的session数据
        HttpSession session = request.getSession();
        Object employee =session.getAttribute("Employee");
        //判断数据是否为空,为空则为未登录状态,反之则为登录状态
        if (employee != null){
            chain.doFilter(request,response);
           return;
        }

        if(request.getSession().getAttribute("user") != null){
            chain.doFilter(request,response);
            return;
        }
        //Filter不会自动将字符串转换为json字符串,需要手动转
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().print(jsonString);



    }

    public void init(FilterConfig config) throws ServletException {

    }



}
